package com.huluobo.a2109amvvmdemo.lifecycle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import com.huluobo.a2109amvvmdemo.viewmodel.ADViewModel;
import com.huluobo.a2109amvvmdemo.viewbinding.MainActivity;
import com.huluobo.a2109amvvmdemo.R;

/**
 * LifeCycle总结
 * 1.如果需要使用LifeCycle,首先需要实现一个接口,LifeCycleObserver,让实现他的类可以去感知宿主的生命周期(观察者)
 * 2.需要一个宿主,LifeCycleOwner,一般来说AppCompatActivity 已经实现了宿主接口,可以直接使用,不需要再次实现(被观察者)
 * 3.通过getLifeCycle.addObserver(xxx),产生订阅关系(订阅关系)
 * 4.可以有效解决宿主对象中控制其他控件的生命周期,让观察者可以根据宿主对象的生命周期自行做出判断,来调用哪些方法
 * 5.MVVM模式是的基础是观察模式,也是基于LifeCycle的
 */
public class ADActivity extends AppCompatActivity {

    private TextView time;
    private Button go;
    private ADManager adManager;

    private ADViewModel adViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adactivity);

        time = findViewById(R.id.time);
        go = findViewById(R.id.btn_go);

        adViewModel = new ViewModelProvider(this).get(ADViewModel.class);

        adManager = new ADManager(adViewModel);
        adViewModel.getTimingResult().observe(this, new Observer<Long>() {
            @Override
            public void onChanged(Long aLong) {
                time.setText("广告剩余时间:" + aLong + "秒");
                if (aLong ==1) {
                    Intent intent = new Intent(ADActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });

        //订阅关系
        getLifecycle().addObserver(adManager);

        go.setOnClickListener(v -> {
            Intent intent = new Intent(ADActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        });
    }
}